import json

from peewee import CharField, IntegerField, DateTimeField, TextField, ForeignKeyField
from playhouse.shortcuts import model_to_dict

from models.base_model import BaseModel
from models.sdn import Vll
from models.user import User, Organization


class WorkOrder(BaseModel):
    TYPE_MAP = (
        ('fault', '故障单'),
        ('service_consultation', '服务咨询'),
    )
    type = CharField(max_length=200, choices=TYPE_MAP, verbose_name='类型')
    FAULT_TYPE_MAP = (
        ('discontinue', '中断'),
        ('loss_packet', '丢包'),
        ('delay', '时延'),
        ('jitter', '抖动'),
        ('slow', '网络慢'),
        ('other', '其他'),
    )
    source_type = CharField(max_length=200, choices=FAULT_TYPE_MAP, null=True, verbose_name='类型')
    STATUS_MAP = (
        ('accepting', '处理中'),
        ('canceled', '已撤销'),
        ('closed', '已关单'),
    )
    status = CharField(max_length=16, choices=STATUS_MAP, default='accepting', verbose_name='状态')
    happen_time = DateTimeField(null=True, verbose_name="发送时间")
    note = TextField(null=True, verbose_name="故障描述")
    contacts = CharField(max_length=64, verbose_name="联系人")
    phone = CharField(max_length=20, verbose_name="联系电话")
    email = CharField(max_length=128, null=True, verbose_name="联系邮箱")
    start_org = ForeignKeyField(Organization, backref='my_faults', null=True, on_delete='CASCADE',
                                verbose_name='发起方')
    user = ForeignKeyField(User, verbose_name='关联成员', on_delete='CASCADE')
    vll_relation = CharField(max_length=255, verbose_name="业务")
    reply_content = TextField(verbose_name="回复")
    no = CharField(max_length=255, null=True, verbose_name='工单编号')
    close_time = DateTimeField(null=True, verbose_name="关单时间")
    file = CharField(max_length=255, null=True, verbose_name='工单文件')

    class Meta:
        db_table = 'xingxiu_work_order'

    def get_standard_obj(self):
        work = model_to_dict(self)
        if work['vll_relation']:
            vll = Vll.get_or_none(Vll.id == work['vll_relation'])
            work['vll_relation'] = {
                "id": vll.id,
                "name": vll.name
            }
        if work['file']:
            work['file'] = json.loads(work['file'])
        return model_to_dict(self)


class WorkOrderChat(BaseModel):
    content = TextField(verbose_name='内容')
    org = ForeignKeyField(Organization, verbose_name='关联组织机构', on_delete='CASCADE', )
    user = ForeignKeyField(User, verbose_name='关联成员', on_delete='CASCADE', )
    work = ForeignKeyField(WorkOrder, verbose_name='关联成员', on_delete='CASCADE', )

    class Meta:
        db_table = 'xingxiu_work_order_chat'
